# Proc Ex4 Makefile — src -> bin build with debug helpers
# Usage:
#   make            # release build (optimized)
#   make DEBUG=1    # debug build (no optimizations, -g)
#   make debug      # same as DEBUG=1
#   make show       # print key variables
#   make print-FOO  # print value of variable FOO
#   make clean      # remove built binaries

# Compiler and dirs
CC ?= gcc
SRC_DIR := src
BIN_DIR := bin
INCLUDE_DIR := include

# Tasks
TASKS := lab4_task1 lab4_task2 lab4_task3 lab4_task4 lab4_task5
SRCS := $(addprefix $(SRC_DIR)/,$(addsuffix .c,$(TASKS)))
BINS := $(addprefix $(BIN_DIR)/,$(TASKS))

# Tool helpers (portable defaults for POSIX-like envs)
RM ?= rm -f
RMDIR ?= rm -rf
MKDIR_P ?= mkdir -p

# Flags
STD := -std=c11
COMMON_WARN := -Wall -Wextra -Werror=implicit-function-declaration
CFLAGS_RELEASE := -O2 -DNDEBUG $(COMMON_WARN) $(STD)
CFLAGS_DEBUG   := -O0 -g3 -DDEBUG $(COMMON_WARN) $(STD)

# Verbosity (set V=1 for verbose)
ifeq ($(V),1)
  Q :=
else
  Q := @
endif

# Select flags by DEBUG
ifeq ($(DEBUG),1)
  CFLAGS := $(CFLAGS_DEBUG)
else
  CFLAGS := $(CFLAGS_RELEASE)
endif

CPPFLAGS := -I$(INCLUDE_DIR)
LDLIBS :=
LDFLAGS :=

.PHONY: all debug clean show print-%

all: $(BINS)

# Debug build convenience target
debug: DEBUG=1
debug: all

# Ensure bin directory exists
$(BIN_DIR):
	$(Q)$(MKDIR_P) $(BIN_DIR)

# Build each task
$(BIN_DIR)/%: $(SRC_DIR)/%.c | $(BIN_DIR)
	@echo [CC] $< -> $@
	$(Q)$(CC) $(CPPFLAGS) $(CFLAGS) $< -o $@ $(LDFLAGS) $(LDLIBS)

# Variable introspection
print-%:
	@echo $*=$($*)

show:
	@echo CC=$(CC)
	@echo DEBUG=$(DEBUG)
	@echo V=$(V)
	@echo CFLAGS=$(CFLAGS)
	@echo CPPFLAGS=$(CPPFLAGS)
	@echo LDFLAGS=$(LDFLAGS)
	@echo LDLIBS=$(LDLIBS)
	@echo SRC_DIR=$(SRC_DIR)
	@echo BIN_DIR=$(BIN_DIR)
	@echo INCLUDE_DIR=$(INCLUDE_DIR)
	@echo SRCS=$(SRCS)
	@echo BINS=$(BINS)

# Clean built binaries only (keep logs/data)
clean:
	$(Q)$(RM) $(BINS)